package com.liruo.treasureattic.authserver.component;

import com.liruo.treasureattic.authserver.model.SecurityUser;
import com.liruo.treasureattic.common.config.properties.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:liruo
 * @Date:2022-10-09-22:20:49
 * @Desc
 */
//@Component
//@Slf4j
public class JwtTokenEnhancer implements TokenEnhancer {
    @Resource
    private JwtProperties jwtProperties;
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> additionalInformation = oAuth2AccessToken.getAdditionalInformation();
        Object principal = oAuth2Authentication.getPrincipal();
        if(principal instanceof String){
//            log.info("principal = {}",principal);
        }else if(principal instanceof SecurityUser){
            SecurityUser user = (SecurityUser) principal;
//            log.info("principal = user:{}", user);
            HashMap<String, Object> info = new HashMap<>(1);
            info.put(jwtProperties.getUserIdentity(), user.getId());
            ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(info);
        }
        return oAuth2AccessToken;
    }
}
